<?php
namespace Admin\Controller;
use Common\Controller\CommonFunctionController;
class LoginController extends CommonFunctionController{

    /**
     * 后台管理系统登录页
     */
	public function index()
	{

        $this->assign('config', self::get_sys_config());
        $this->display();
	}



    /**
	 * 用户登录,验证用户名和密码
     */
    public function doLogin()
    {
        if(IS_POST && IS_AJAX){
            $post = I('post.');
            $post['username'] = trim($post['username']);
            $post['password'] = trim($post['password']);
            if(empty($post['username'])){
                self::response('400','请输入账号');
            }
            if(empty($post['password'])){
                self::response('400','请输入账号');
            }
            $userM = M('user');
            $where = array();
            $where['username'] = $post['username'];
            $user = $userM->where($where)->find();
            if(empty($user)){
                self::response('400','账号或密码错误');
            }
            if($user['status'] != 1){
                self::response('400','账号审核中');
            }
            $password = md5($post['password'].$user['salt']);
            if ($user['password'] != $password) {
                self::response('400','账号或密码错误');
            }
            session('admin', $user);

            //记录最后登录时间
            $userM->where(array('id'=>$user['id']))->save(array('last_login_time'=>NOW_TIME));

            if($user['type'] == 1){
                //管理员

            }elseif($user['type'] == 2){
                //药企
                $drug_companyM = M('drug_company');
                $company = $drug_companyM->where(array('uid'=>$user['id']))->find();
                session('company', $company);
            }elseif($user['type'] == 3){
                //药店
                $drug_storeM = M('drug_store');
                $company = $drug_storeM->where(array('uid'=>$user['id']))->find();
                session('company', $company);
            }else{
                self::response('400','用户错误');
            }

            $redirect = U('Home/index');
            self::response('200','登录成功', array('redirect'=>$redirect));
        }
    }

    /**
     * 统一退出登陆接口
     */
    public function doLogout()
    {
        session('admin', null);
        $this->redirect('Admin/Login/index');
    }
}
